package service

import (
	"LogisticsPort/model"
	"LogisticsPort/sql"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Car(r *gin.Engine) {
	car := r.Group("/car")
	{
		car.POST(sql.RequestAdd, carAdd)
		car.POST(sql.RequestUpdate, carUpdate)
		car.GET(sql.RequestList, carList)
		car.GET(sql.RequestData, carData)
		car.GET(sql.RequestDelete, carDelete)

	}
}

func carAdd(c *gin.Context) {
	sql.HttpHandle(sql.ADD, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		var bean model.CarInfo
		if err := c.Bind(&bean); err != nil {
			db.Error = err
			return db, nil
		}
		if err := db.Transaction(func(tx *gorm.DB) error {
			var list []model.CarInfo
			if bean.PlateNumber != "" { //车牌号不为空时进行查重判断
				if err := tx.Where("plate_number = ?", bean.PlateNumber).Find(&list).Error; err != nil {
					return err
				}
				if len(list) > 0 {
					return errors.New("车牌号已存在，请重新录入")
				}
			} else if bean.LogisticsCompany == "" { // 车号为空时，必须有物流公司
				return errors.New("请确认物流公司")
			}

			if err := tx.Create(&bean).Error; err != nil {
				return err
			}
			return nil
		}); err != nil {
			db.Error = err
			return db, nil
		}
		return db, bean
	})
}

func carUpdate(c *gin.Context) {
	sql.HttpHandle(sql.ADD, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		var bean model.CarInfo
		if err := c.Bind(&bean); err != nil {
			db.Error = err
			return db, nil
		}
		if err := db.Transaction(func(tx *gorm.DB) error {
			var list []model.CarInfo
			if err := tx.Where("plate_number = ? AND id != ?", bean.PlateNumber, bean.Id).Find(&list).Error; err != nil {
				return err
			}
			if len(list) > 0 {
				return errors.New("车牌号已存在，请重新录入")
			}
			if err := tx.Save(&bean).Error; err != nil {
				return err
			}
			return nil
		}); err != nil {
			db.Error = err
			return db, nil
		}
		return db, bean
	})
}

func carDelete(c *gin.Context) {
	sql.HttpHandle(sql.DELETE, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		var id = c.Query("id")
		if id == "" {
			db.Error = errors.New(sql.ErrorParams)
			return db, nil
		}
		err := db.Transaction(func(tx *gorm.DB) error {
			var productFlowList []model.ProductFlow
			if err := tx.Where("car_id =?", id).Find(&productFlowList).Error; err != nil {
				return err
			}
			if len(productFlowList) > 0 {
				return errors.New("已关联销售信息，不可删除")
			}
			if err := tx.Where("id = ?", id).Delete(&model.CarInfo{}).Error; err != nil {
				return err
			}
			return nil
		})
		if err != nil {
			db.Error = err
			return db, nil
		}
		return db, nil
	})
}

func carData(c *gin.Context) {
	sql.HttpDataById(c, &model.CarInfo{})
}

func carList(c *gin.Context) {
	sql.HttpList(c, &[]model.CarInfo{}, func(db *gorm.DB) *gorm.DB {
		search := c.Query("search")
		db = db.
			Where("sales_area LIKE ?", "%"+search+"%").
			Or("plate_number LIKE ?", "%"+search+"%").
			Or("logistics_company LIKE ?", "%"+search+"%").
			Or("driver_phone LIKE ?", "%"+search+"%").
			Order("id DESC")
		return db
	})
}
